<template>
  <div class="register-container">
    <div class="register-title">注册</div>
    <van-form validate-first>
      <!-- 通过 pattern 进行正则校验 -->
      <van-field v-model.trim="phone" label="手机号" name="pattern" placeholder="请输入手机号" maxlength="11">
        <template #button>
          <van-button size="small" type="primary" color="#0C34BA" @click="getEmailValidatorCode" v-if="flag">发送验证码</van-button>
          <van-button size="small" type="primary" color="#0C34BA" disabled v-else>{{ timeCount }}s后重新发送</van-button>
        </template>
      </van-field>
      <!-- 验证码 -->
      <van-field v-model.trim="code" label="验证码" name="pattern" placeholder="验证码(6位数字)" maxlength="6" />

      <!-- 账号 -->
      <van-field v-model.trim="account" label="账号" name="账号" placeholder="请输入账号" maxlength="64" />

      <!-- 通过 validator 进行函数校验 -->
      <van-field v-model.trim="password" :type="text" label="密码" name="validator" placeholder="密码(6-16位)" :right-icon="eye" maxlength="16" @click-right-icon="toggleEye" />
      <van-field v-model.trim="nickname" label="昵称" placeholder="昵称(1-10位)" maxlength="32" />
      <div class="login-btn">
        <van-button class="register-btn" round block @click="onSubmit">注册</van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { Notify } from 'vant'
import axios from '@/utils/request/request'

export default {
  name: 'register-view',
  data() {
    return {
      eye: 'closed-eye',
      text: 'password',
      phone: '',
      code: '',
      password: '',
      nickname: '',
      account: '',
      pattern: /^1[3-9]\d{9}$/,
      codePattern: /^\d{6}$/,
      timeCount: 60,
      timer: null,
      flag: true
    }
  },
  methods: {
    toggleEye() {
      if (this.eye === 'closed-eye') {
        this.eye = 'eye-o'
        this.text = 'text'
      } else {
        this.eye = 'closed-eye'
        this.text = 'password'
      }
    },
    // 获取验证码
    async getEmailValidatorCode() {
      // 手机号不能为空并且格式不能错误
      if (this.phone == '') {
        return Notify({
          type: 'danger',
          message: '请输入手机号！'
        })
      }
      if (!/^1[3-9]\d{9}$/.test(this.phone)) {
        return Notify({
          type: 'danger',
          message: '手机号格式错误！'
        })
      }
      this.$toast.loading({
        duration: 0,
        message: '加载中...',
        loadingType: 'spinner'
      })
      try {
        // 发起请求获取验证码
        const data = await axios.post('/api/getcode', {
          phone: this.phone
        })
        // 获取成功
        if (data.code === 0) {
          this.flag = false
          Notify({
            type: 'success',
            message: '验证码发送成功，请注意查收！'
          })
          this.timer = setInterval(() => {
            this.timeCount--
            if (this.timeCount <= 0) {
              clearInterval(this.timer)
              this.timeCount = 60
              this.flag = true
            }
          }, 1000)
        } else {
          this.$toast.clear()
          Notify({
            type: 'danger',
            message: data.msg,
            duration: 1000
          })
        }
      } catch {
        Notify({
          type: 'danger',
          message: '请求失败！',
          duration: 1000
        })
      } finally {
        this.$toast.clear()
      }
    },
    // 发起注册请求
    async onSubmit() {
      // 手机号不能为空并且格式不能错误
      if (this.phone == '') {
        return Notify({
          type: 'danger',
          message: '请输入手机号！'
        })
      }
      if (!/^1[3-9]\d{9}$/.test(this.phone)) {
        return Notify({
          type: 'danger',
          message: '手机号格式错误！'
        })
      }

      // 验证验证码是否正确
      if (this.code === '') {
        return Notify({
          type: 'danger',
          message: '请输入验证码！'
        })
      }
      if (!this.codePattern.test(this.code)) {
        return Notify({
          type: 'danger',
          message: '验证码为6位有效数字！'
        })
      }

      // 验证账号
      if (this.account === '')
        return Notify({
          type: 'danger',
          message: '请输入账号！'
        })
      if (this.account.length > 64)
        return Notify({
          type: 'danger',
          message: '账号最大长度为64位！'
        })

      // 密码验证
      if (this.password === '')
        return Notify({
          type: 'danger',
          message: '请输入密码！'
        })
      if (!/^(?=.*[a-zA-Z])(?=.*[0-9])[A-Za-z0-9]{6,16}$/.test(this.password))
        return Notify({
          type: 'danger',
          message: '密码必须为6-16的数字字母组合！'
        })

      // 验证昵称
      if (this.nickname === '')
        return Notify({
          type: 'danger',
          message: '请输入昵称！'
        })
      if (this.nickname.length > 32)
        return Notify({
          type: 'danger',
          message: '用户昵称最大长度为32位！'
        })

      this.$toast.loading({
        duration: 0,
        message: '加载中...',
        loadingType: 'spinner'
      })
      try {
        // 发起请求注册账号
        const data = await axios.post('/api/user/register', {
          phone: this.phone,
          code: this.code,
          account: this.account,
          password: this.password,
          nickname: this.nickname
        })

        if (data.code === 0) {
          // 清空表单数据
          this.phone = ''
          this.code = ''
          this.account = ''
          this.password = ''
          this.nickname = ''
          // 隐藏注册表单
          this.$emit('hideRegisterForm')
          Notify({
            type: 'success',
            message: data.msg,
            duration: 1000
          })
        } else {
          this.$toast.clear()
          Notify({
            type: 'danger',
            message: data.msg,
            duration: 1000
          })
        }
      } catch {
        Notify({
          type: 'danger',
          message: '请求失败！',
          duration: 1000
        })
      } finally {
        this.$toast.clear()
      }
    }
  }
}
</script>

<style lang="less" scoped>
.register-container {
  padding: 10px;
  height: 100%;
  box-sizing: border-box;

  .register-title {
    height: 30px;
    margin-bottom: 20px;
    color: #444;
    font-size: 24px;
  }

  .login-btn {
    margin-top: 50px;
    margin-bottom: 20px;

    .register-btn {
      background-color: #f92946;
      color: white;
      border: 1px solid #f92946;
    }
  }

  /deep/ .van-field--error .van-field__control,
  /deep/ .van-field--error .van-field__control::placeholder {
    color: rgba(50, 50, 50, 0.5);
    -webkit-text-fill-color: currentColor;
  }
}
</style>
